package com.woniu.dating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.common.entity.ResultCode;
import com.woniu.common.exception.LifeException;
import com.woniu.dating.constant.DatingConstant;
import com.woniu.dating.dto.GameTestDTO;
import com.woniu.dating.mapper.DatingHobbyMapper;
import com.woniu.dating.mapper.DatingInfoMapper;
import com.woniu.dating.pojo.DatingGame;
import com.woniu.dating.mapper.DatingGameMapper;
import com.woniu.dating.pojo.DatingHobby;
import com.woniu.dating.pojo.DatingInfo;
import com.woniu.dating.service.IDatingGameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.dating.vo.DatingLoginVO;
import com.woniu.dating.vo.MatchingDatingVO;
import com.woniu.dating.vo.RecommendVO;
import com.woniu.user.feignClient.UserFeignClient;
import com.woniu.user.pojo.User;
import org.apache.ibatis.annotations.ResultType;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 玖柒
 * @since 2023-05-20
 */
@Service
public class DatingGameServiceImpl extends ServiceImpl<DatingGameMapper, DatingGame> implements IDatingGameService {

    @Resource
    private DatingGameMapper datingGameMapper;

    @Resource
    private DatingHobbyMapper datingHobbyMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private DatingInfoMapper datingInfoMapper;


    /**
     * 查询用户游戏记录
     */
    @Override
    public DatingGame getDatingGame(DatingLoginVO datingLoginVO) {
        DatingGame datingGame = datingGameMapper.getDatingGame(datingLoginVO.getUserId());
        return datingGame;
    }

    /**
     * 将用户的游戏记录添加进去
     * @param gameTestDTO
     * @param datingLoginVO
     */
    @Override
    public void addDatingGame(GameTestDTO gameTestDTO, DatingLoginVO datingLoginVO) {
        //1.创建一个实体类对象，存储数据
        DatingGame datingGame = new DatingGame();
        //2.用户填入的答案存入对象中
        BeanUtils.copyProperties(gameTestDTO,datingGame);
        //3.将用户信息传入对象中
        datingGame.setUserId(datingLoginVO.getUserId());
        datingGame.setGender(datingLoginVO.getGender());
        //4.添加记录
        datingGameMapper.insert(datingGame);
    }

    /**
     * 修改游戏记录
     */
    @Override
    public void updateDatingGame(GameTestDTO gameTestDTO, DatingLoginVO datingLoginVO, Integer id) {
        DatingGame datingGame = new DatingGame();
        BeanUtils.copyProperties(gameTestDTO,datingGame);
        datingGame.setUserId(datingLoginVO.getUserId());
        datingGame.setGender(datingLoginVO.getGender());
        datingGame.setId(id);
        datingGameMapper.updateById(datingGame);
    }

    /**
     * 匹配异性，按照匹配度返回对象id.
     */
    @Override
    public void listMatchingDating(DatingLoginVO datingLoginVO) {
        //1.查询出当前用户的答案
        DatingGame datingGame = datingGameMapper.getDatingGame(datingLoginVO.getUserId());
        //。查询出异性的答案集合
        List<DatingGame> datingGameList = null;
        QueryWrapper gameWrapper = new QueryWrapper();
        //3.如果为男性用户
        if (datingLoginVO.getGender().equals(DatingConstant.DATING_BOY)) {
            gameWrapper.eq("gender",DatingConstant.DATING_GIRL);
            datingGameList = datingGameMapper.selectList(gameWrapper);
        }
        //4.如果为女性用户
        if (datingLoginVO.getGender().equals(DatingConstant.DATING_GIRL)) {
            gameWrapper.eq("gender",DatingConstant.DATING_BOY);
            datingGameList = datingGameMapper.selectList(gameWrapper);
        }
        //5.遍历集合,匹配用户的答案，将相同答案，且匹配度大于60，存入redis中
        for (DatingGame datingGameNew : datingGameList) {
            //定义初始变量值
            Integer num = DatingConstant.DATING_MATCHING;
            //每成功一次匹配就加20匹配度
            if (datingGameNew.getQuestionOne().equals(datingGame.getQuestionOne())) {
               num = num+DatingConstant.DATING_ADD_NUM;
            }
            if (datingGameNew.getQuestionTwo().equals(datingGame.getQuestionTwo())) {
                num = num+DatingConstant.DATING_ADD_NUM;
            }
            if (datingGameNew.getQuestionThree().equals(datingGame.getQuestionThree())) {
                num = num+DatingConstant.DATING_ADD_NUM;
            }
            if (datingGameNew.getQuestionFour().equals(datingGame.getQuestionFour())) {
                num = num+DatingConstant.DATING_ADD_NUM;
            }
            if (datingGameNew.getQuestionFive().equals(datingGame.getQuestionFive())) {
                num = num+DatingConstant.DATING_ADD_NUM;
            }
            //当匹配度大于60时，将该对象的id放入redis中
            if (num >= DatingConstant.DATING_TARGET_NUM) {
              redisTemplate.opsForList().leftPush(DatingConstant.DATING_MATCHING_KEY,datingGameNew.getUserId());
            }
            num = DatingConstant.DATING_MATCHING;
        }

    }

    /**
     * 返回匹配结果
     */
    @Override
    public List<RecommendVO> listMatchingOutcome(DatingLoginVO datingLoginVO) {
        //获取redis中存入的id
        //创建集合，存储数据
        List<RecommendVO> listRecommendVO = null;
        for (int i = DatingConstant.DATING_FOR_ONE; i <= DatingConstant.DATING_FOR_FIVE ; i++) {
            //,从左边存，从右边取，每次取5条
            Integer userId = (Integer) redisTemplate.opsForList().rightPop(DatingConstant.DATING_MATCHING_KEY + datingLoginVO.getUserId());
            //根据id,查询出用户放入集合中
            if (userId == null) {
                //，如果为空，抛出异常，已查看完所有结果
                throw new LifeException(ResultCode.DATING_GAME_NULL.getMessage());
            }
            RecommendVO recommendVO = datingHobbyMapper.getDatingHobbyByUserId(userId);
            listRecommendVO.add(recommendVO);
        }
        return listRecommendVO;
    }

    /**
     * 支付2比特币，生成查看记录，当前用户扣两颗，被查看用户加一颗
     */
    @Override
    @Transactional
    public void payBitcoin(Integer userId, DatingLoginVO datingLoginVO) {
        // 1.判断当前用户的比特币余额
        User currentUser = userFeignClient.getUser(datingLoginVO.getUserId()).getData();
        if (currentUser.getBitcoin().compareTo(DatingConstant.DATING_BITCOIN) < DatingConstant.DATING_COMPARE_TO) {
            throw new LifeException(ResultCode.DATING_BITCOIN_INSUFFICIENT.getMessage());
        }
        // 2.余额足够，当前用户扣两颗，被查看用户加一颗
        currentUser.setBitcoin(currentUser.getBitcoin().subtract(DatingConstant.DATING_BITCOIN_TWO));
        userFeignClient.updateAmount(datingLoginVO.getMobile(),DatingConstant.DATING_BITCOIN_TWO);
        //修改被查看用户的比特币
        User user = userFeignClient.getUser(userId).getData();
        userFeignClient.addAmount(user.getMobile(),DatingConstant.DATING_BITCOIN_ONE);
        //3.新增一条查看记录
        DatingInfo datingInfo = new DatingInfo();
        datingInfo.setUserId(user.getId());
        datingInfo.setCurrentId(datingLoginVO.getUserId());
        datingInfoMapper.insert(datingInfo);
    }
}
